module.exports = app => {
  const express = require('express')
  const adminjwt = require('jsonwebtoken')

  const router = express.Router({
    mergeParams: true
    // 合并参数
  })
  const Category = require('../../models/Category')
  const AdminUser = require('../../models/AdminUser')

  // 引入资源中间件
  const resourceMiddleware = require('../../middleware/resource')
  const authMiddleware = require('../../middleware/auth')
  // rest表示通用接口
  app.use(require('cors')()) // 跨域
  app.use(express.json()) // 使用json
  app.use('/admin/api/rest/:resource',authMiddleware(),resourceMiddleware(), router)

  // 查询全部
  router.get('/', async (req, res) => {
    //.populate 将关联字段的全部信息获取出来
    // if (req.Model === 'Merchandise') {
    //   var items = await req.Model.find().populate('categories')
    //   res.send(items)
    //   return
    // }
    // var items = await req.Model.find().populate('parent', 'categories')
    if (req.ModelName === 'Order') {
      var items = await req.Model.find().populate('buyer')
      res.send(items)
      return
    }
    var items = await req.Model.find()
    res.send(items)
  })
  //创建
  router.post('/',async (req,res) => {
    var model = await req.Model.create(req.body)
    res.send(model)
  })
  // 查询单个
  router.get('/:id', async (req, res) => {
    var items = await req.Model.findById(req.params.id)
    res.send(items)
  })
  // 修改
  router.put('/:id',async (req, res) => {
    console.log(req.params);
    let {resource} = req.params
    var model
    switch (resource) {
      case 'orders':
        model = await req.Model.findByIdAndUpdate(req.params.id,{ mailnumber: req.body.mailnumber, orderstate: '已发货'})
        break
        default: 
        model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
      break
    }
    res.send(model)
  })
  // 删除
  router.delete('/:id',async (req, res) => {
    var model = await req.Model.findByIdAndDelete(req.params.id, req.body)
    res.send({
      success: '成功'
    })
  })
  
  app.use(require('cors')()) // 跨域
  app.use(express.json()) // 使用json
  // 查询第一级分类 （parent 无内容）
  app.get('/admin/api/parentCategories', async (req, res) => {
    //.populate 将关联字段的全部信息获取出来
    var items = await Category.find({parent: {$exists:false}})
    res.send(items)
  })
  // 查询子分类
  app.get('/admin/api/childCategories/:id', async (req, res) => {
    // 父级分类id & 查询参数
    var parentId, query
    // 父级分类名
    var item = await Category.findById(req.params.id)
    var name = item.name
    
    // console.log(req.params.name);
    // 通过名称查询父级分类 id
    await Category.find({ name: name }).then(data => {
      if (data.length) {
        parentId = data[0]._id
      }
      query = {
        parent: parentId
      }
    })
    await Category
      .find(query).populate('parent')
      .exec((err, data) => {
        err && res.send({ code: 0, msg: err.errmsg })
        res.send({ code: 1, data })
      })
  })


  // 上传图片接口
  const multer = require('multer')
  const fs = require('fs')
  const path = require('path')
  const upload = multer({ dest: __dirname + '/../../uploads'})
  app.use('/admin/api/upload', upload.single('file') ,async (req,res) => {
    const file = req.file
    let oldname = file.path //获取path: 'public\\upload\\0f625978d5d1a783b12e149718f8b634',
    let newname = file.path + path.parse(file.originalname).ext //.jpg
    fs.renameSync(oldname, newname)//将老的文件名改成新的有后缀的文件 #同步写法
    file.url = 'http://localhost:3001/uploads/'+file.filename+path.parse(file.originalname).ext
    res.send(file)
  })

  // 登录接口
  app.use('/admin/api/login', async (req,res) => {
    const { username, password } = req.body
    // 1.验证用户是否存在  .select('+password') 把select：false 的密码强制拿出来
    const user = await AdminUser.findOne({ username }).select('+password')
    if(!user) {
      return res.status(422).send({
        message: '用户不存在'
      })
    }
    // 2。验证密码
    const isValid = require('bcryptjs').compareSync(password, user.password)
    if (!isValid) {
      return res.status(422).send({
        message: '密码错误'
      })
    }
    // 3.返回token
    const token = adminjwt.sign({ id:user._id }, app.get('secret'))
    res.send(token)
  })
}